<?php

namespace app\http\middleware;

use think\Config;

class Check
{
    public function handle($request, \Closure $next)
    {
        header("Access-Control-Allow-Origin:*");
        header('Access-Control-Allow-Credentials: true');
        header("Access-Control-Allow-Methods:*");
        header("Access-Control-Allow-Headers:Content-Type,Access-Token,X-Token");
        header("Access-Control-Expose-Headers:*");
        if($_SERVER['REQUEST_METHOD'] == 'OPTIONS'){
            exit;
        }
        define('ROOT_TOKEN','2Q3ntNqyo5eaLmXITABb');
        $module = $request->module();//模块名
        $controller = $request->controller();//控制器名
        $action = $request->action();//方法名
        $is_except=in_array($module.'/'.$controller.'/'.$action,Config('except_check.'));

        if(!$is_except && $module!=='generate'){
            // --- 需要token访问的接口 ---
            $_data['token']=input('token');
            //获取token信息（account_id、expires_in、create_time、end_time）
            $data=get_curl('login','token/info',$_data);
            //判断token是否存在
            if($data['status']){
                //判断是否有权限访问
                $token=$data['data'];
                define('ACCOUNTID',$token['account_id']);
            }else{
                echo \tools\curl\Curl::arr2json(['status'=>false,'msg'=>'Token不可用',"error"=>$data]);
                //停止往后运行方法
                die;
            }
        }
        define('SYSSIGN', 'base');
        if (preg_match('~micromessenger~i', $request->header('user-agent'))) {
            $request->InApp = 'WeChat';
        } else if (preg_match('~alipay~i', $request->header('user-agent'))) {
            $request->InApp = 'Alipay';
        }
        if (SYSSIGN) {
            $request->sys_sign = SYSSIGN;
        }
        $pagesize=input('pagesize')?input('pagesize'):input('limit');
        if($pagesize){
            Config('paginate.list_rows',$pagesize);
        }
        return $next($request);
    }
}